<template>
  <div class="websoket-box">
    <input type="text" placeholder="请输入内容" ref="input" v-model="msgValue">
    <button ref="btn" @click="sendMsg">发送消息</button>
    <div class="content" ref="msg"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      levelList: null,
      adminIds: '',
      tokens: '',
      merIds: '',
      webSocket: null,
      lockReconnect: false,//是否真正建立连接
      timeout: 10000,//5秒一次心跳
      timeoutObj: null,//心跳心跳倒计时
      serverTimeoutObj: null,//心跳倒计时
      timeoutnum: null,//断开 重连倒计时
      TYPE_ENTER:0,
      TYPE_LEAVE:1,
      TYPE_MSG:2,
      msgValue:'',//发送的消息
    }
  },
  created() {
    this.initWebSocket();
  },
  mounted(){
    // console.log(this.$refs.msg);
  },
  methods: {
    initWebSocket() {
      //初始化weosocket
     /*  let url = 'ws://localhost:3003'
      const wsuri = url; //ws地址 */
      this.websocket = new WebSocket('ws://localhost:3003');
      console.log(this.websocket );
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      this.websocket.onmessage = this.websocketonmessage;
      this.websocket.onclose = this.websocketclose;
    },
    sendMsg(){
     this.msgValue = this.$refs.input.value;
     this.websocket.send(this.msgValue);
     this.msgValue = ''
    },
    reconnect() {//重新连接
      var that = this;
      if (that.lockReconnect) {
        return;
      }
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function () {
        //新连接
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
    websocketonopen() {//连接成功事件
      console.log("WebSocket连接成功");
      //开启心跳
      this.start();
    },
    websocketonerror(e) {//连接失败事件
      //错误
      console.log("WebSocket连接发生错误",e);
      //重连
      this.reconnect();
    },
    websocketclose(e) {//连接关闭事件
      //关闭
      console.log("WebSocket关闭",e);
      console.log("connection closed (" + e.code + ")");
      //重连
      this.reconnect();
    },
    websockOpen() {//打开连接
      console.log("WebSocket连接成功");
      this.start();
    },
    websocketonmessage(e) { //数据接收
      console.log(e.data);
      let data =JSON.parse(e.data)
      let dv = document.createElement("div")
      dv.innerHTML = data.msgg+'-----'+data.time
      if(data.type === this.TYPE_ENTER){
        dv.style.color = 'green'
      }else if(data.type === this.TYPE_LEAVE){
        dv.style.color = 'red'
      }else{
        dv.style.color = 'blue'
      }
      // console.log(this.$refs.msg);
      this.$refs.msg.appendChild(dv)
      //收到服务器信息，心跳重置
      this.reset();
    },
    start() {
      console.log('开启心跳');
      const self = this;
      let _num = 3;
      self.timeoutObj && clearTimeout(self.timeoutObj);
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self.timeoutObj = setTimeout(function () {

        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (self.websocket.readyState === 1) {//如果连接正常     

          //   高亮！！网上代码都是self.websock.readyState 
          // console.log(self.websocket.readyState);
          self.websocket.send("heartCheck");

        } else {//否则重连
          console.log('545')
          self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function () {
          // console.log(_num)
          //超时关闭
          _num--;
          //计算答复的超时次数
          if (_num === 0) {
            self.reconnect();
          }
        }, self.timeout);

      }, self.timeout)
    },
    reset() {
      console.log('重置心跳');
      var that = this;
      //清除时间
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      //重启心跳
      that.start();
    },


  },
}
</script>
